"""
工时管理相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from datetime import datetime
from sqlalchemy import func
from app.models import db, User, Project, ProjectTask, WorkHour

# 创建蓝图
work_hour_bp = Blueprint('work_hour', __name__, url_prefix='/work_hour')

@work_hour_bp.route('/')
@login_required
def list_work_hours():
    """工时记录列表"""
    work_hours = WorkHour.query.filter_by(user_id=current_user.id).all()
    
    # 计算总工时
    total_work_hours = sum([wh.work_hours for wh in work_hours]) if work_hours else 0
    
    # 计算本月工时
    from datetime import date
    today = date.today()
    current_month = today.month
    current_year = today.year
    monthly_work_hours = sum([
        wh.work_hours for wh in work_hours 
        if wh.work_date and wh.work_date.month == current_month and wh.work_date.year == current_year
    ]) if work_hours else 0
    
    # 获取进行中的任务数
    active_tasks_count = ProjectTask.query.filter_by(assignee_id=current_user.id, status='进行中').count()
    
    # 计算工时偏差
    work_hour_deviation = 0
    if work_hours:
        # 获取用户的所有任务及其估算工时
        user_tasks = ProjectTask.query.filter_by(assignee_id=current_user.id).all()
        total_estimated = sum([task.estimated_hours for task in user_tasks if task.estimated_hours]) or 0
        total_actual = total_work_hours
        
        if total_estimated > 0:
            work_hour_deviation = total_actual - total_estimated
    
    # 准备最近工时记录数据
    recent_work_hours = []
    for wh in work_hours[-10:]:  # 获取最近10条记录
        task = ProjectTask.query.get(wh.task_id) if wh.task_id else None
        project = Project.query.get(wh.project_id) if wh.project_id else None
        
        recent_work_hours.append({
            'project_name': project.name if project else '未知项目',
            'task_name': task.name if task else '未知任务',
            'hours': wh.work_hours,
            'start_time': wh.start_time.strftime('%Y-%m-%d %H:%M') if wh.start_time else None,
            'end_time': wh.end_time.strftime('%Y-%m-%d %H:%M') if wh.end_time else None,
            'user_name': current_user.username,
            'project_id': wh.project_id
        })
    
    return render_template('work_hour_management.html', 
                          work_hours=work_hours,
                          total_work_hours=total_work_hours,
                          monthly_work_hours=monthly_work_hours,
                          active_tasks_count=active_tasks_count,
                          work_hour_deviation=work_hour_deviation,
                          recent_work_hours=recent_work_hours)

@work_hour_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create():
    """创建工时记录"""
    if request.method == 'POST':
        project_id = request.form.get('project_id')
        task_id = request.form.get('task_id')
        work_date = datetime.strptime(request.form.get('work_date'), '%Y-%m-%d').date()
        hours = float(request.form.get('hours'))
        description = request.form.get('description')
        
        # 创建工时记录
        work_hour = WorkHour(
            user_id=current_user.id,
            project_id=project_id,
            task_id=task_id,
            work_date=work_date,
            hours=hours,
            description=description
        )
        
        db.session.add(work_hour)
        db.session.commit()
        
        flash('工时记录创建成功')
        return redirect(url_for('work_hour.list_work_hours'))
    
    # 获取项目列表
    projects = Project.query.filter_by(manager_id=current_user.id).all()
    
    # 获取任务列表并按状态分类
    all_tasks = ProjectTask.query.filter_by(assignee_id=current_user.id).all()
    not_started_tasks = [task for task in all_tasks if task.status == '未开始']
    in_progress_tasks = [task for task in all_tasks if task.status == '进行中']
    completed_tasks = [task for task in all_tasks if task.status == '已完成']
    closed_tasks = [task for task in all_tasks if task.status == '已关闭']
    
    return render_template('work_hour_create.html', 
                          projects=projects, 
                          not_started_tasks=not_started_tasks,
                          in_progress_tasks=in_progress_tasks,
                          completed_tasks=completed_tasks,
                          closed_tasks=closed_tasks)

@work_hour_bp.route('/<int:work_hour_id>/edit', methods=['GET', 'POST'])
@login_required
def edit(work_hour_id):
    """编辑工时记录"""
    work_hour = WorkHour.query.filter_by(id=work_hour_id, user_id=current_user.id).first()
    
    if not work_hour:
        flash('您没有权限编辑此工时记录')
        return redirect(url_for('work_hour.list_work_hours'))
    
    if request.method == 'POST':
        project_id = request.form.get('project_id')
        task_id = request.form.get('task_id')
        work_date = datetime.strptime(request.form.get('work_date'), '%Y-%m-%d').date()
        hours = float(request.form.get('hours'))
        description = request.form.get('description')
        
        work_hour.project_id = project_id
        work_hour.task_id = task_id
        work_hour.work_date = work_date
        work_hour.work_hours = hours
        work_hour.description = description
        
        db.session.commit()
        
        flash('工时记录更新成功')
        return redirect(url_for('work_hour.list_work_hours'))
    
    # 获取项目列表
    projects = Project.query.filter_by(manager_id=current_user.id).all()
    
    # 获取任务列表并按状态分类
    all_tasks = ProjectTask.query.filter_by(assignee_id=current_user.id).all()
    not_started_tasks = [task for task in all_tasks if task.status == '未开始']
    in_progress_tasks = [task for task in all_tasks if task.status == '进行中']
    completed_tasks = [task for task in all_tasks if task.status == '已完成']
    closed_tasks = [task for task in all_tasks if task.status == '已关闭']
    
    return render_template('work_hour_create.html', 
                          work_hour=work_hour, 
                          projects=projects, 
                          not_started_tasks=not_started_tasks,
                          in_progress_tasks=in_progress_tasks,
                          completed_tasks=completed_tasks,
                          closed_tasks=closed_tasks)

@work_hour_bp.route('/<int:work_hour_id>/delete', methods=['POST'])
@login_required
def delete(work_hour_id):
    """删除工时记录"""
    work_hour = WorkHour.query.filter_by(id=work_hour_id, user_id=current_user.id).first()
    
    if not work_hour:
        flash('您没有权限删除此工时记录')
    else:
        db.session.delete(work_hour)
        db.session.commit()
        flash('工时记录删除成功')
    
    return redirect(url_for('work_hour.list_work_hours'))

@work_hour_bp.route('/report')
@login_required
def report():
    """工时报告"""
    start_date = request.args.get('start_date')
    end_date = request.args.get('end_date')
    
    if start_date and end_date:
        start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
        work_hours = WorkHour.query.filter(
            WorkHour.user_id == current_user.id,
            WorkHour.work_date >= start_date,
            WorkHour.work_date <= end_date
        ).all()
    else:
        work_hours = None
    
    # 计算统计数据
    total_work_hours = 0
    active_projects = []
    active_users = []
    avg_work_hours = 0
    
    if work_hours:
        # 计算总工时
        total_work_hours = sum([wh.work_hours for wh in work_hours])
        
        # 获取活跃项目
        project_ids = set([wh.project_id for wh in work_hours if wh.project_id])
        active_projects = Project.query.filter(Project.id.in_(project_ids)).all()
        
        # 获取活跃用户（包括当前用户）
        user_ids = set([current_user.id])
        active_users = User.query.filter(User.id.in_(user_ids)).all()
        
        # 计算平均工时
        if active_users:
            avg_work_hours = total_work_hours / len(active_users)
    
    # 准备报告数据，用于模板中的循环
    report_data = active_users
    
    # 准备报告摘要数据
    report_summary = {
        'total_hours': total_work_hours,
        'total_estimated_hours': total_work_hours * 0.9,  # 假设估算工时为实际工时的90%
        'total_actual_hours': total_work_hours,
        'total_deviation_hours': total_work_hours * 0.1,  # 假设偏差工时为实际工时的10%
        'total_tasks': len(active_users),
        'total_cost': total_work_hours * 100  # 假设每小时成本为100元
    }
    
    # 设置报告类型和标题
    report_type = 'user'  # 默认为用户报告
    report_title = '工时统计报告'
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    return render_template('work_hour_report.html', 
                          work_hours=work_hours, 
                          start_date=start_date, 
                          end_date=end_date,
                          total_work_hours=total_work_hours,
                          active_projects=active_projects,
                          active_users=active_users,
                          avg_work_hours=avg_work_hours,
                          report_data=report_data,
                          report_type=report_type,
                          report_summary=report_summary,
                          report_title=report_title,
                          current_time=current_time)

@work_hour_bp.route('/deviation')
@login_required
def work_hour_deviation():
    """工时偏差分析"""
    # 获取工时偏差统计数据
    from app.services import WorkHourService
    deviation_stats = WorkHourService.get_deviation_stats(current_user.id)
    deviation_tasks = WorkHourService.get_deviation_tasks(current_user.id)
    projects = Project.query.filter_by(manager_id=current_user.id).all()
    users = User.query.all()
    
    # 准备图表数据
    deviation_chart_data = {
        'categories': [task['name'][:10] + '...' if len(task['name']) > 10 else task['name'] for task in deviation_tasks[:10]],
        'estimated_hours': [task['estimated_hours'] for task in deviation_tasks[:10]],
        'actual_hours': [task['actual_hours'] for task in deviation_tasks[:10]]
    }
    
    # 准备偏差原因图表数据
    deviation_reason_chart_data = {
        'categories': ['需求变更', '技术难度', '资源不足', '沟通问题', '其他'],
        'data': [
            {'value': 30, 'name': '需求变更'},
            {'value': 25, 'name': '技术难度'},
            {'value': 20, 'name': '资源不足'},
            {'value': 15, 'name': '沟通问题'},
            {'value': 10, 'name': '其他'}
        ]
    }
    
    return render_template('work_hour_deviation.html', 
                         deviation_stats=deviation_stats,
                         deviation_tasks=deviation_tasks,
                         deviation_chart_data=deviation_chart_data,
                         deviation_reason_chart_data=deviation_reason_chart_data,
                         projects=projects,
                         users=users)

@work_hour_bp.route('/stats')
@login_required
def stats():
    """工时统计"""
    # 获取项目ID参数
    project_id = request.args.get('project_id', type=int)
    
    # 获取用户管理的项目
    projects = Project.query.filter_by(manager_id=current_user.id).all()
    
    # 默认统计数据
    stats = {
        'total_work_hours': 0,
        'total_cost': 0,
        'total_projects': len(projects),
        'total_tasks': 0
    }
    
    selected_project = None
    tasks = []
    costs = []
    work_hour_records = []
    
    # 如果指定了项目ID，获取项目相关数据
    if project_id:
        selected_project = Project.query.filter_by(id=project_id, manager_id=current_user.id).first()
        if selected_project:
            # 获取项目任务
            tasks = ProjectTask.query.filter_by(project_id=project_id).all()
            stats['total_tasks'] = len(tasks)
            
            # 计算项目总工时
            work_hours = WorkHour.query.filter_by(project_id=project_id).all()
            stats['total_work_hours'] = sum([wh.work_hours for wh in work_hours])
            
            # 获取工时记录详情
            for wh in work_hours:
                task = ProjectTask.query.get(wh.task_id) if wh.task_id else None
                user = User.query.get(wh.user_id) if wh.user_id else None
                
                if task and user:
                    work_hour_records.append((wh, task, user))
    
    # 获取用户任务列表（用于添加工时记录）
    user_tasks = ProjectTask.query.filter_by(assignee_id=current_user.id).all()
    
    # 准备用户工时分布数据
    user_work_hours = []
    if selected_project:
        # 如果选择了项目，获取项目中所有用户的工时数据
        user_ids = db.session.query(WorkHour.user_id).filter_by(project_id=project_id).distinct().all()
        for user_id_tuple in user_ids:
            user_id = user_id_tuple[0]
            user = User.query.get(user_id)
            if user:
                user_hours = db.session.query(func.sum(WorkHour.work_hours)).filter_by(
                    project_id=project_id, user_id=user_id
                ).scalar() or 0
                user_work_hours.append({
                    'user': user,
                    'hours': user_hours
                })
    else:
        # 如果没有选择项目，获取当前用户所有项目的工时数据
        user_hours = db.session.query(func.sum(WorkHour.work_hours)).filter_by(
            user_id=current_user.id
        ).scalar() or 0
        user_work_hours.append({
            'user': current_user,
            'hours': user_hours
        })
    
    return render_template('work_hour_stats.html',
                         stats=stats,
                         projects=projects,
                         selected_project=selected_project,
                         tasks=tasks,
                         costs=costs,
                         work_hour_records=work_hour_records,
                         user_tasks=user_tasks,
                         user_work_hours=user_work_hours)